package com.easyfun.healthmagicbox.comm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

import com.easyfun.healthmagicbox.base.DatabaseAccess;
import com.easyfun.healthmagicbox.base.DatabaseAccessImplementation;
import com.easyfun.healthmagicbox.comm.json.DoctorAndSugListJsonWrapper;
import com.easyfun.healthmagicbox.ormlite.DatabaseHelper;
import com.easyfun.healthmagicbox.ormlite.ServerResponseCode;
import com.easyfun.healthmagicbox.pojo.ConstantData;
import com.easyfun.healthmagicbox.pojo.DoctorAndSuggestion;
import com.easyfun.healthmagicbox.pojo.DoctorProfile;
import com.easyfun.healthmagicbox.sync.BasicCommCallback;
import com.easyfun.healthmagicbox.sync.CommCallback;
import com.j256.ormlite.dao.Dao;

public class SuggestionDownloadTask extends BaseCommTask implements Runnable,
		DatabaseAccess {
	private final static String LOG_TAG = SuggestionDownloadTask.class.getSimpleName();
	String mpersonalID;

	public SuggestionDownloadTask(Context context, String persionID,
			CommCallback callback) {

		super(context,callback);
		mpersonalID = persionID;
	}

	@Override
	public void run() {
		try {

			List<String> doctorIDs = new ArrayList<String>();
			Dao<DoctorAndSuggestion, Integer> dao = getHelper(mcontext)
					.getDoctorSuggestionDao();
			long max = dao
					.queryRawValue(
							"select max(suggestionsyncid) from DoctorAndSuggestion where personID = ?",
							mpersonalID);

			if (max > -1) {

				JSONObject serializedObj = new JSONObject();
				serializedObj.put("personID", mpersonalID);
				serializedObj.put("suggestionsyncid", max);

				Map<String, String> parmas = new HashMap<String, String>();
				parmas.put("jsonstring", serializedObj.toString());
				String result = super.uploadByHTTP(parmas,
						ConstantData.DoctorDownloadSuggesionURI);
				if(ServerResponseCode.parseOf(result)==ServerResponseCode.NOMORE)
				{
					ccb.setCommResult(this,
							mpersonalID, ServerResponseCode.NOMORE);
					return;
				}else if (ServerResponseCode.parseOf(result)==ServerResponseCode.FAILED)
				{
					ccb.setCommResult(this,
							mpersonalID, ServerResponseCode.FAILED);
					return;
				}
				
				if ((result.length() > 0)) {
					
						DoctorAndSugListJsonWrapper<?> wrapper = DoctorAndSugListJsonWrapper.
								getInstance(result, DoctorAndSugListJsonWrapper.class);
						
						List<DoctorAndSuggestion> sugs = wrapper.getMpps();
						
						for (DoctorAndSuggestion sug:sugs)
						{
							max = dao
									.queryRawValue(
											"select max(suggestionsyncid) from DoctorAndSuggestion where personID = ?",
											mpersonalID);
							if (sug.getSuggestionsyncid() > max)
							{
								dao.create(sug);
								doctorIDs.add(sug.getDoctorID());
							}
						}

						Dao<DoctorProfile, Integer> doctorProfileDao = getHelper(mcontext)
								.getDoctorProfileDao();
						for (String doctorid:doctorIDs)
						{
							List<DoctorProfile> doctors = doctorProfileDao.queryBuilder().where().eq("doctorID",doctorid).query();
							if (doctors.size() < 1)
							{
								BasicCommCallback dpccb = new BasicCommCallback();
								DoctorProfileDownloadTask task = new DoctorProfileDownloadTask(
										doctorid, 
										mcontext, 
										dpccb
										);
								HealthThreadPool.getInstance().execute(task);
								ServerResponseCode src = dpccb.getCommResult(
										DoctorProfileDownloadTask.class, "");
								int i = 0;
								while ((src==ServerResponseCode.WAITING) && (i<50))
								{
									synchronized (dpccb) {
										try {
											dpccb.wait(100);
										} catch (InterruptedException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
									src = dpccb.getCommResult(DoctorProfileDownloadTask.class, "");
									i++;
								}
							}
						}
						ccb.setCommResult(this,
								mpersonalID, ServerResponseCode.SUCCESS);
					
				}else
				{
					ccb.setCommResult(this,
							mpersonalID, ServerResponseCode.FAILED);
				}

			}
		} catch (Exception e) 
		{
			Log.e(LOG_TAG, e.toString());
			e.printStackTrace();
			ccb.setCommResult(this,
					mpersonalID, ServerResponseCode.FAILED);
		}

	}

	@Override
	public DatabaseHelper getHelper(Context context) {

		return DatabaseAccessImplementation.getInstance().getHelper(mcontext);
	}
}
